﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using CxExtension;
using UnityEngine;

namespace VersionControl
{
	[Serializable]
	public class AssetInfo
	{
		public string Name;//
		public string AssetBundleName;//
		public string Variant;//
		public List<string> DependenceList;
		public bool HasVariant => Variant.IsNullOrEmpty() == false;

		public AssetInfo()
		{
			
		}
		public AssetInfo(string name, string assetBundleName)
		{
			Name = name;
			AssetBundleName = assetBundleName;
			Variant = string.Empty;
		}

	}
	public enum StoreRootPathId
	{
		StreamingPath = 1,//
		ReadWritePath = 2,//
	}

	[Serializable]
	public class AssetBundleVersionInfo:IComparable<AssetBundleVersionInfo>,IComparer<AssetBundleVersionInfo>
	{
		public string ApplicableGameVersion;//
		public int InternalResourceVersion;//
		public bool isEncrypt = false;
		public byte EncryptKey = 0;
		public List<AssetBundleInfo> AssetBundleList;//
		public List<AssetBundleVariantInfo> AssetBundleVariantList;//
		private static Func<string, AssetBundleVersionInfo> mParseFunc;                      //
		public static void SetParseFunction(Func<string, AssetBundleVersionInfo> parseFunc)
		{
			mParseFunc = parseFunc;
		}

		public static AssetBundleVersionInfo Create(string path)
		{
			var str = File.ReadAllText(path);
			var versionInfo = mParseFunc==null ? JsonUtility.FromJson<AssetBundleVersionInfo>(str) : mParseFunc(str);
			return versionInfo;

		}
		public static AssetBundleVersionInfo Parse(byte[] bytes)
		{
			var str = Encoding.UTF8.GetString(bytes);
			var versionInfo = mParseFunc == null?JsonUtility.FromJson<AssetBundleVersionInfo>(str):mParseFunc(str);
			return versionInfo;
		}
		public static AssetBundleVersionInfo Max(params AssetBundleVersionInfo[] list)
		{
			switch (list.Length)
			{
				case 0:
					return null;
				case 1:
					return list[0];
				case 2 when CompareS(list[0],list[1]) >= 0:
					return list[0];
				case 2:
					return list[1];
				default:
					return list.Max();
			}
		}
		public static int CompareS(AssetBundleVersionInfo a, AssetBundleVersionInfo b)
		{
			var aNull = a == null;
			var bNull = b == null;
			if (aNull && bNull)
			{
				return 0;
			}
			if (aNull || bNull)
			{
				return bNull ? 1 : -1;
			}

			var ac = a.InternalResourceVersion;
			var bc = b.InternalResourceVersion;
			if (ac == bc)
			{
				return 0;
			}

			return ac > bc ? 1 : -1;
		}
		#region Implementation of IComparable<in AssetBundleVersionInfo>

		public int CompareTo(AssetBundleVersionInfo other)
		{
			return CompareS(this, other);
		}

		#endregion

		#region Implementation of IComparer<in AssetBundleVersionInfo>

		public int Compare(AssetBundleVersionInfo x, AssetBundleVersionInfo y)
		{
			return CompareS(x, y);
		}

		#endregion
	}
}